package iit.projects.etaxi.model.dao;

import iit.projects.etaxi.model.entity.ReceivedSms;
import iit.projects.etaxi.util.Constants;

import java.util.Calendar;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class HibernateSmsDao extends HibernateDaoSupport implements SmsDao {

	final Logger log = LoggerFactory.getLogger(HibernateSmsDao.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public List<ReceivedSms> findReceivedSmsByStatus(String status) {
		if(log.isDebugEnabled()){
			log.debug("Going to find ReceivedSms by status " + status + " at " + Calendar.getInstance().getTime());
		}
		
		Session session = getSession(false);
		
		try{
			Criteria criteria = session.createCriteria(ReceivedSms.class);
			criteria.add(Restrictions.eq("status", status));
			
			List<ReceivedSms> list = criteria.list();
			return list;
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
	}
	
	@Override
	public void updateSmsToProcessed(List<ReceivedSms> reveivedSms){
		if(log.isDebugEnabled()){
			log.debug("Going to update Received SMS List");
		}
		
		Session session = getSession(false);
		
		if(reveivedSms == null || reveivedSms.isEmpty()){
			return;
		}
		try{
			for(ReceivedSms sms : reveivedSms){
				sms.setStatus(Constants.SmsStatus.PROCESSED);
				session.merge(sms);
			}
		}catch(HibernateException ex){
			throw convertHibernateAccessException(ex);
		}
		
	}

}
